package 线程;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author:谢君臣
 * @Date:2021/9/13-14:48
 * @version:1.0
 * @function:
 */
public class CountDownLanch {
    public static void main(String[] args) {
        Resource resource = new Resource();
        resource.run();
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Resource implements Runnable{
    private volatile int state = 10;
    private CountDownLatch countDownLatch = new CountDownLatch(state);
    @Override
    public void run() {
        try {
            new Thread(()->{
                System.out.println("主线程任务开始");
                for (int i = 0; i < 10; i++) {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    countDownLatch.countDown();
                    System.out.println("----完成了一个任务！剩余任务：" + countDownLatch.getCount());
                }
            }).start();
            System.out.println("主线程：等待分线程任务结束！");
            countDownLatch.await();
            System.out.println("主线程：分线程任务结束！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}